package com.changjiang.luban.utils.oss;

import com.changjiang.luban.utils.GenerateCodeUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * CosUtils
 * Description:
 *
 * @author nichangjiang@vip.qq.com
 * @version v0.1
 * @date 2018/6/13 - 18:23
 */
public class CosUtils {

    /** appId */
    public static final String APP_ID = "1251438932";

    /** 密钥id */
    public static final String SECRET_ID = "AKIDb7SdfWjh3EE6rXxWp153tbFmCUxPdwCN";

    /** 密钥key */
    public static final String SECRET_KEY = "AB5pVL7i9QxKafZLyTp04QnNrAKKBsOl";

    /** 设置bucket所在的区域 华东园区：sh */
    public static final String SH_REGION = "ap-shanghai";

//    public static final String POSTER_BUCKET_NAME = "luban";

    public static final String POSTER_BUCKET_NAME = "poster";

    /**
     * 初始化客户端对象
     * @return
     */
    public static COSClient getCOSClient() {
        // 初始化秘钥信息
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig(new Region(SH_REGION));
        return new COSClient(cred, clientConfig);
    }

    public static String uploadFile(String bucketName,File cosFile) {
        COSClient cosClient = getCOSClient();
        String cosKey = GenerateCodeUtils.getUUId(1);
        bucketName = bucketName+"-"+APP_ID;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,cosKey,cosFile);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, cosKey, expiration);
        return "http://"+url.getHost()+url.getPath();
    }

}
